# encoding=utf-8
# 整理 hibernate 反向过程实体类的代码
import re, os


def r(p):
    f = open(p)
    c = f.read()
    f.close()
    return c


def fmt(s):
    s = re.sub(r'new HashSet<[^>]+?>\(0?\)', 'new HashSet<>()', s)
    s = re.sub(r'/\*[\w\W]+?\*/', '', s)  # 去区块注释
    s = re.sub(r'\n\s*//[^\n]+', '', s)  # 去单行注释
    s = re.sub(r'return this\.', 'return ', s)

    if re.search(r'@Table\(.+?,?\s*?catalog = "\w+?"\)', s):
        s = re.sub(r'(@Table\(.+?),?\s*?catalog = "\w+?"(?=\))', r'\1', s)

    if s.find('java.io.Serializable') >= 0:
        s = s.replace('java.io.Serializable', 'Serializable')
        s = s.replace('import ', 'import java.io.Serializable;\nimport ', 1)

    if re.search(r'import static javax\.persistence\.GenerationType\.\w+', s):
        s = re.sub(r'import static (javax\.persistence\.GenerationType)\.\w+', r'import \1', s)
        s = re.sub(r'strategy\s*=\s*(\w+)', r'strategy=GenerationType.\1', s)

    if not re.search(r'\bserialVersionUID\b', s):
        s = re.sub(r'(public class [\w\.\s]+?\{)', r'\1\nprivate static final long serialVersionUID = 1;', s)

    s = re.match(r'([\w\W]*?public class [^\{]+?\{)([\s\S]+)\}\s*$', s)
    b = s.group(2)  # 类内部
    s = s.group(1)

    d = {}
    # {成员变量名:相应注解}
    while 1:
        b1 = re.search(r'[;\}]\s*(@[\w\W]+?)public .+?\(\)\s*\{\s*return (\w+)\b', b)
        if not b1: break
        b = b.replace(b1.group(1), '', 1)
        d[b1.group(2)] = b1.group(1)

    for i in d:
        b = re.sub(r'(private .+? ' + i + r'\b)', d[i] + r'\1', b)

    s += b + '}'

    s = re.sub(r'[\r\n]+\s*[\r\n]+', r'\n', s)  # 去连续多行
    s = re.sub(r';\s*[\r\n](?=\s*?@)', r';\n\n', s)
    return s


p = r'C:\Users\Administrator\Workspaces\MyEclipse 2016\hibernate\src\entity'

for i in os.listdir(p):
    print i
    i = os.path.join(p, i)
    s1 = fmt(r(i))
    f = open(i, 'w')
    f.write(s1)
    f.close()
